#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QRegularExpressionValidator>
#include <QTextBlock>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    refreshDPI();
    myusbthread = new USBThread(this);
    connect(myusbthread,SIGNAL(new_data(const QByteArray)),this,SLOT(usbreceivedata(const QByteArray)));
    connect(myusbthread,SIGNAL(usb_connect(QString)),this,SLOT(usbconnect(QString)));
    connect(myusbthread,SIGNAL(usb_disconnect()),this,SLOT(usbdisconnect()));
    connect(myusbthread,SIGNAL(usb_send_error()),this,SLOT(usbsenderror()));

    myusbthread->vid = DEFAULT_VENDOR_ID;
    myusbthread->pid = DEFAULT_PRODUCT_ID;
    myusbthread->start();
    qDebug() << myusbthread->vid << "|" << myusbthread->pid << endl;
    hid_device_list = myusbthread->get_device_list();
    device_nums = hid_device_list.size();
    ui->comboBox_device->clear();
    foreach (HidDeviceInfo i, hid_device_list)
    {
        if(!hid_device_num.contains(i.path))
            hid_device_num.insert(i.path, hid_device_num.size());
        ui->comboBox_device->addItem(tr("GX_LINK#%1").arg(hid_device_num[i.path]), i.path);
    }
    device_nums = hid_device_list.size();
    systimer = new QTimer(this);
    connect(systimer,SIGNAL(timeout()),this,SLOT(systimerUpdate()));
    systimer->start(2000);
    sender_timer = new QTimer(this);
    connect(sender_timer, SIGNAL(timeout()), this, SLOT(sender_update()));
    refresh_button();
}

MainWindow::~MainWindow()
{
    if(myusbthread->isRunning())
    {
        myusbthread->stop_thread();
        myusbthread->wait();
    }
#if DEBUG_WRITE_BIN_FILE
    if(save_debug_bin.isOpen())
        save_debug_bin.close();
#endif

    delete ui;
}

//刷新dpi
void MainWindow::refreshDPI()
{
    //计算dpi
    QList<QScreen*> screens = QApplication::screens();
    QScreen* screen = screens[0];
    qreal dpi = screen->logicalDotsPerInch();
    //计算dpi对应的缩放比例
    double objectRate = dpi/96.0;
    changeObjectSize(*this, objectRate);
    qDebug()<<"width "<<width() << "height "<< height();
    resize(width()*objectRate,height()*objectRate);
}
//修改所有控件尺寸
void MainWindow::changeObjectSize(const QObject &o, double objectRate)
{
    for (int i=0; i<o.children().size(); ++i) {
        QWidget *pWidget = qobject_cast<QWidget *>(o.children().at(i));
        if (pWidget != nullptr) {
            qDebug() << pWidget->width() << pWidget->height();
            //pWidget->resize(pWidget->width()*objectRate, pWidget->height()*objectRate);
            pWidget->setGeometry(pWidget->x()*objectRate,pWidget->y()*objectRate,
                                 pWidget->width()*objectRate, pWidget->height()*objectRate);
            changeObjectSize(*(o.children().at(i)),objectRate);
        }
    }
}

void MainWindow::systimerUpdate()
{
    if(!hid_isopen)
    {
        hid_device_list = myusbthread->get_device_list();
        qDebug() << "device_nums:" << device_nums << "|hid_device_list:" << hid_device_list.size();
        if(device_nums != hid_device_list.size())
        {
            ui->comboBox_device->clear();
            foreach (HidDeviceInfo i, hid_device_list)
            {
                if(!hid_device_num.contains(i.path))
                    hid_device_num.insert(i.path, hid_device_num.size());
                ui->comboBox_device->addItem(tr("GX_Link #%1").arg(hid_device_num[i.path]), i.path);
            }
            device_nums = hid_device_list.size();
        }
    }
}


void MainWindow::usbconnect(QString dev_str)
{
    qDebug() << "usbconnect";
    hid_isopen = true;
    refresh_button();
    //ui->textEdit_information->append("设备已连接");
    //ui->textEdit_information->append("设备名称:"+dev_str);
}

void MainWindow::usbdisconnect()
{
    qDebug() << "usbdisconnect";
    hid_isopen = false;
    refresh_button();
    ui->textEdit_information->append(QString::fromUtf8(u8"设备已断开"));
}

void MainWindow::usbsenderror()
{
    qDebug() << "usbsenderror";
    myusbthread->pause_thread();
    //QMessageBox::warning(this,QString::fromUtf8(u8"错误"),QString::fromUtf8(u8"USB发送数据异常"),QMessageBox::Ok);
}

void MainWindow::sender_update()
{
    qDebug() << "sender_update";
    if(downloading)
    {
        if(write_end_flash)
        {
            QByteArray data_send;
            data_send.append((char)(0x00));
            data_send.append(hex_parser.flash_end_data);
            send_bin_data(WRITEA_FLASH_PC_TO_MCU, data_send);
            download_count++;
            download_end_count++;
            if(download_end_count >= 6)
            {
                write_end_flash = false;
                sender_timer->stop();
#ifdef DOWNLOAD_AND_CHECK
                check_count--;
                checking_end = true;
                check_data();
#else
                //WRITE16_IN_PC_TO_MCU 00 20  00 0B
                {
                    QByteArray gen_data;
                    gen_data.append(1,0x00);
                    gen_data.append(1,0x20);
                    gen_data.append(1,0x00);
                    gen_data.append(1,0x0B);
                    send_data(WRITE16_IN_PC_TO_MCU, gen_data);
                }
                refresh_button();
                ui->textEdit_information->append(QString::fromUtf8(u8"下载成功:") + QDateTime::currentDateTime().toString("hh:mm:ss.zzz"));
#endif
            }
        }
        else
        {
            QByteArray data_send;
            data_send.append((char)(0x00));
            if(write_flash)
            {
                data_send.append(hex_parser.flash_data.mid(download_count*DEFAULT_BIN_PACKAGE_SIZE,DEFAULT_BIN_PACKAGE_SIZE));
                send_bin_data(WRITEA_FLASH_PC_TO_MCU, data_send);
            }
            else
            {
                data_send.append(hex_parser.bin_data.mid(download_count*DEFAULT_BIN_PACKAGE_SIZE,DEFAULT_BIN_PACKAGE_SIZE));
                send_bin_data(WRITEN_MCU_PC_TO_MCU, data_send);
            }
            download_count += 1;
            ui->progressBar_Download_Speed->setValue((int)(download_count*DEFAULT_BIN_PACKAGE_SIZE*100/hex_parser.bin_data.size()));
            if(hex_parser.bin_data.size() <= download_count*DEFAULT_BIN_PACKAGE_SIZE)
            {
                sender_timer->stop();
#if DEBUG_WRITE_BIN_FILE
            if(save_debug_bin.isOpen())
                save_debug_bin.close();
#endif
                if(write_flash)
                {
                    Delay_MSec(30);
                    check_count = 0;
#ifdef DOWNLOAD_AND_CHECK
                    ui->textEdit_information->append(QString::fromUtf8(u8"下载成功,正在校验:") + QDateTime::currentDateTime().toString("hh:mm:ss.zzz"));
                    check_data();
#else
                    download_end_count = 0;
                    write_end_flash = true;
                    sender_timer->start(1);
#endif
                }
                else
                {
                    //MCU 02 0x00000000
                    {
                        QByteArray gen_data;
                        gen_data.append(1,0x02);
                        gen_data.append(4,0x00);
                        send_data(WRITE32_MCU_PC_TO_MCU, gen_data);
                    }

                    //MCU read 01
                    {
                        QByteArray gen_data;
                        gen_data.append((char)0x01);
                        send_data(READ32_MCU_PC_TO_MCU, gen_data);
                    }
                    downloading = false;
                    refresh_button();
                    ui->textEdit_information->append(QString::fromUtf8(u8"下载成功:") + QDateTime::currentDateTime().toString("hh:mm:ss.zzz"));
                    if(1)
                    {
                        ui->textEdit_information->append(QString::fromUtf8(u8"运行程序..."));
                        QByteArray gen_data;
                        gen_data.append((char)0x01);
                        send_data(RESET_MCU_MCU_TO_PC, gen_data);
                    }
                }
            }
        }
    }
    else
    {
        if(repeated_count < repeated_time)
        {
            myusbthread->send_data(last_send_data);
            repeated_count++;
        }
        else
        {
            sender_timer->stop();
        }
    }
}

void MainWindow::usbreceivedata(const QByteArray recv_data)
{
    //qDebug() << recv_data.toHex(' ');
    //ui->plainTextEdit_receive->appendPlainText(recv_data.toHex(' '));
    if((recv_data.at(0) == (char)WRITEN_MCU_MCU_TO_PC) && downloading)
    {
        int new_count = (uchar)recv_data.at(2);
        new_count = new_count*256+(uchar)recv_data.at(3);
        qDebug() << "Repeat Send :" << new_count;
        //ui->textEdit_information->append(tr("Repeat Send :%1").arg(new_count));
        download_count = new_count;
        download_end_count--;
    }
    if((recv_data.at(0) == (char)HELLO_MCU_TO_PC))
    {
        qDebug() << recv_data.toHex(' ');
        QString mtlink_version = "0x" + recv_data.mid(4,4).toHex(0);
        QString MCU_ID = "0x" + recv_data.mid(8,8).toHex(0);
        QString Flash_ID = "0x" + recv_data.mid(16,2).toHex(0);
        QString USB_ID = "0x" + recv_data.mid(18,6).toHex(0);
//        ui->textEdit_information->append(tr("mtlink_version :%1").arg(mtlink_version));
        ui->textEdit_information->append(QString::fromUtf8(u8"找到可操作设备：")+tr("%1").arg(MCU_ID));
//        ui->textEdit_information->append(tr("Flash_ID :%1").arg(Flash_ID));
//        ui->textEdit_information->append(tr("USB_ID :%1").arg(USB_ID));
    }
    if(recv_data.at(0) == (char)READA_FLASH_MCU_TO_PC && checking)
    {
        checking = false;
        if(checking_end)
        {
            uint32_t read_data_size = (uchar)recv_data.at(1) - 4 - 3;
            uint32_t read_addr = ((uchar)recv_data.at(4))*256*256 + ((uchar)recv_data.at(5))*256 + ((uchar)recv_data.at(6));
            int data_cout = (read_addr - 0x000200)/DEFAULT_BIN_PACKAGE_SIZE;

            QByteArray read_data = recv_data.mid(7,read_data_size);

            QByteArray flash_data = hex_parser.flash_data.mid(data_cout*DEFAULT_BIN_PACKAGE_SIZE,read_data_size);
            qDebug() << "Read Data:" << read_data.toHex(' ');
            qDebug() << "Flash Data:" << flash_data.toHex(' ');

            if(read_data.left(flash_data.size()) != flash_data)
            {
                ui->textEdit_information->append(QString::fromUtf8(u8"数据校验失败,请重新下载！") + QDateTime::currentDateTime().toString("hh:mm:ss.zzz"));
                //ui->textEdit_information->append("尾部数据校验失败,请重新下载！" + QDateTime::currentDateTime().toString("hh:mm:ss.zzz"));
                QTimer::singleShot(10, this, SLOT(redownload_data()));
                return;
            }
            if(read_data.right(read_data.size()-flash_data.size()) != hex_parser.flash_end_data.left(read_data.size()-flash_data.size()))
            {
                ui->textEdit_information->append(QString::fromUtf8(u8"数据校验失败,请重新下载！") + QDateTime::currentDateTime().toString("hh:mm:ss.zzz"));
                //ui->textEdit_information->append("尾部数据校验失败,请重新下载！" + QDateTime::currentDateTime().toString("hh:mm:ss.zzz"));
                //error download
                QTimer::singleShot(10, this, SLOT(redownload_data()));
                return;
            }
            checking_end = false;
            //ui->textEdit_information->append("尾部数据校验成功,下载完成:" + QDateTime::currentDateTime().toString("hh:mm:ss.zzz"));
            ui->textEdit_information->append(QString::fromUtf8(u8"校验成功,下载完成:") + QDateTime::currentDateTime().toString("hh:mm:ss.zzz"));
            //WRITE16_IN_PC_TO_MCU 00 20  00 0B
            {
                QByteArray gen_data;
                gen_data.append(1,0x00);
                gen_data.append(1,0x20);
                gen_data.append(1,0x00);
                gen_data.append(1,0x0B);
                send_data(WRITE16_IN_PC_TO_MCU, gen_data);
            }
            downloading = false;
            refresh_button();
        }
        else
        {
            uint32_t read_data_size = (uchar)recv_data.at(1) - 4 - 3;
            uint32_t read_addr = ((uchar)recv_data.at(4))*256*256 + ((uchar)recv_data.at(5))*256 + ((uchar)recv_data.at(6));
            int data_cout = (read_addr - 0x000200)/DEFAULT_BIN_PACKAGE_SIZE;
            QByteArray read_data = recv_data.mid(7,read_data_size);
            QByteArray flash_data = hex_parser.flash_data.mid(data_cout*DEFAULT_BIN_PACKAGE_SIZE,read_data_size);
            if(read_data == flash_data)
            {
                check_count++;
                if(check_count*DEFAULT_BIN_PACKAGE_SIZE >= hex_parser.flash_data.size())
                {
                    //ui->textEdit_information->append("校验成功,正在写入尾部数据:" + QDateTime::currentDateTime().toString("hh:mm:ss.zzz"));
                    download_end_count = 0;
                    write_end_flash = true;
                    sender_timer->start(20);
                }
                else
                {
                    check_data();
                }
            }
            else
            {
                ui->textEdit_information->append(tr("%1").arg(data_cout) + QString::fromUtf8(u8"校验失败,请重新下载！") + QDateTime::currentDateTime().toString("hh:mm:ss.zzz"));
                qDebug() << "Read Data:" << read_data.toHex(' ');
                qDebug() << "Flash Data:" << flash_data.toHex(' ');
                QTimer::singleShot(10, this, SLOT(redownload_data()));
                return;
            }
        }
    }
}


void MainWindow::on_pushButton_openclose_clicked()
{
    if(!hid_isopen){
        if(myusbthread->get_usbstatus() != USB_CONNECT)
        {
            QString usb_path = ui->comboBox_device->currentData().toString();
            if(usb_path.isEmpty()){
                QMessageBox::warning(this,"error",QString::fromUtf8(u8"USB打开失败,请检查设备！"),QMessageBox::Ok);
                return;
            }
            hid_isopen = myusbthread->open_usb(usb_path);
            if(!hid_isopen){
                QMessageBox::warning(this,"error",QString::fromUtf8(u8"USB打开失败,请检查设备！"),QMessageBox::Ok);
            }
        }
    }
    else{
        myusbthread->pause_thread();
    }
}

void MainWindow::on_pushButton_OpenFile_clicked()
{
    ui->textEdit_information->append(QString::fromUtf8(u8"打开文件..."));
    QString fileName = QFileDialog::getOpenFileName(this,QString::fromUtf8(u8"打开固件文件"), QDir::currentPath(), QString::fromUtf8(u8"HEX文件(*.hex)"));
    qDebug()<<"文件名:  "+fileName;

    if(fileName.isEmpty())
        return;
    ui->lineEdit_FileName->setText(fileName);
    hex_parser.clear();
    load_bin = hex_parser.parse(fileName);
    if(!load_bin)
    {
        QMessageBox::warning(this,"error",hex_parser.error_info,QMessageBox::Ok);
        ui->textEdit_information->append(fileName+QString::fromUtf8(u8" 解析失败"));
        return;
    }
    //ui->textEdit_information->append(fileName+" 解析成功, bin长度:" + tr("%1").arg(hex_parser.bin_data.size()-16));
    ui->textEdit_information->append(fileName+QString::fromUtf8(u8"成功"));
    refresh_button();
    //ui->pushButton_StartDownload->setEnabled(hid_isopen & load_bin & !downloading);
}


void MainWindow::on_pushButton_StartDownload_clicked()
{
    if(!load_bin || !hid_isopen || downloading)
        return;
    sender_timer->stop();
    write_flash = false;
    hex_parser.clear();
    load_bin = hex_parser.parse(ui->lineEdit_FileName->text());
    if(!load_bin)
    {
        QMessageBox::warning(this,"error",hex_parser.error_info,QMessageBox::Ok);
        ui->textEdit_information->append(ui->lineEdit_FileName->text()+QString::fromUtf8(u8" 解析失败"));
        return;
    }
#if DEBUG_WRITE_BIN_FILE
    if(save_debug_bin.isOpen())
        save_debug_bin.close();
    save_debug_bin.setFileName("download.bin");
    save_debug_bin.open(QIODevice::WriteOnly|QIODevice::Text|QIODevice::Truncate);
#endif
    download_data();
}

void MainWindow::check_data()
{
    char check_size = DEFAULT_BIN_PACKAGE_SIZE;

    uint32_t read_addr = 0x000200 + check_count*DEFAULT_BIN_PACKAGE_SIZE;
    QByteArray gen_data;

    checking = true;
    if(checking_end)
    {
        check_size = DEFAULT_BIN_PACKAGE_SIZE - ((check_count+1)*DEFAULT_BIN_PACKAGE_SIZE - hex_parser.flash_data.size()) + 16;
    }
    else
    {
        if((check_count+1)*DEFAULT_BIN_PACKAGE_SIZE >= hex_parser.flash_data.size())
        {
            if(check_count*DEFAULT_BIN_PACKAGE_SIZE >= hex_parser.flash_data.size())
            {
                checking = false;
                return;
            }
            check_size = DEFAULT_BIN_PACKAGE_SIZE- ((check_count+1)*DEFAULT_BIN_PACKAGE_SIZE - hex_parser.flash_data.size());
        }
    }
    ui->progressBar_Download_Speed->setValue((int)((check_count+1)*DEFAULT_BIN_PACKAGE_SIZE*100/hex_parser.flash_data.size()));
    gen_data.append(1,check_size);
    gen_data.append((read_addr>>16)&0x0ff);
    gen_data.append((read_addr>>8)&0x0ff);
    gen_data.append((read_addr)&0x0ff);
    send_data(READA_FLASH_PC_TO_MCU, gen_data);
}

void MainWindow::redownload_data()
{
    downloading = false;
    refresh_button();
    //download_data();
}

void MainWindow::download_data()
{
    downloading = true;
    refresh_button();
    download_count = 0;
    ui->progressBar_Download_Speed->setValue(0);
    if(write_flash)
    {
        //flash F6 01 06 00 00
        {
            QByteArray gen_data;
            gen_data.append(1,0x01);
            gen_data.append(1,0x06);
            gen_data.append(2,0x00);
            send_data(WRITEN_FLASH_PC_TO_MCU, gen_data);
        }

        //flash F6 04 D8 00 00 00
        {
            QByteArray gen_data;
            gen_data.append(1,0x04);
            gen_data.append(1,0xD8);
            gen_data.append(3,0x00);
            send_data(WRITEN_FLASH_PC_TO_MCU, gen_data);
        }
        Delay_MSec(30);
        //flash F6 01 06 00 00
        {
            QByteArray gen_data;
            gen_data.append(1,0x01);
            gen_data.append(1,0x06);
            gen_data.append(2,0x00);
            send_data(WRITEN_FLASH_PC_TO_MCU, gen_data);
        }

        //flash F6 04 D8 01 00 00
        {
            QByteArray gen_data;
            gen_data.append(1,0x04);
            gen_data.append(1,0xD8);
            gen_data.append(1,0x01);
            gen_data.append(2,0x00);
            send_data(WRITEN_FLASH_PC_TO_MCU, gen_data);
        }
        Delay_MSec(30);
        //flash F6 01 06 00 00
        {
            QByteArray gen_data;
            gen_data.append(1,0x01);
            gen_data.append(1,0x06);
            gen_data.append(2,0x00);
            send_data(WRITEN_FLASH_PC_TO_MCU, gen_data);
        }

        //flash F6 04 D8 02 00 00
        {
            QByteArray gen_data;
            gen_data.append(1,0x04);
            gen_data.append(1,0xD8);
            gen_data.append(1,0x02);
            gen_data.append(2,0x00);
            send_data(WRITEN_FLASH_PC_TO_MCU, gen_data);
        }
        Delay_MSec(30);
        //HELLO
        {
            QByteArray gen_data;
            gen_data.append((program_version>>24)&0x0ff);
            gen_data.append((program_version>>16)&0x0ff);
            gen_data.append((program_version>>8)&0x0ff);
            gen_data.append((program_version)&0x0ff);
            send_data(HELLO_PC_TO_MCU, gen_data);
        }
        //WRITE16_IN_PC_TO_MCU 00 10  00 02
        {
            QByteArray gen_data;
            gen_data.append(1,0x00);
            gen_data.append(1,0x10);
            gen_data.append(1,0x00);
            gen_data.append(1,0x02);
            send_data(WRITE16_IN_PC_TO_MCU, gen_data);
        }
        //WRITE16_IN_PC_TO_MCU 00 20  00 0C
        {
            QByteArray gen_data;
            gen_data.append(1,0x00);
            gen_data.append(1,0x20);
            gen_data.append(1,0x00);
            gen_data.append(1,0x0C);
            send_data(WRITE16_IN_PC_TO_MCU, gen_data);
        }
        //WRITE16_IN_PC_TO_MCU 00 20  00 0D
        {
            QByteArray gen_data;
            gen_data.append(1,0x00);
            gen_data.append(1,0x20);
            gen_data.append(1,0x00);
            gen_data.append(1,0x0D);
            send_data(WRITE16_IN_PC_TO_MCU, gen_data);
        }
    }
    else
    {
        //RST = 0
        {
            QByteArray gen_data;
            gen_data.append(1,0x00);
            gen_data.append(1,RESET_MCU_MCU_TO_PC);
            gen_data.append(2,0x00);
            send_data(WRITE16_IN_PC_TO_MCU, gen_data);
        }

        //RST = 1
        {
            QByteArray gen_data;
            gen_data.append(1,0x00);
            gen_data.append(1,RESET_MCU_MCU_TO_PC);
            gen_data.append(1,0x00);
            gen_data.append(1,0x01);
            send_data(WRITE16_IN_PC_TO_MCU, gen_data);
        }

        //MCU 00 0x5DF80001
        {
            QByteArray gen_data;
            gen_data.append(1,0x00);
            gen_data.append((char)0x5d);
            gen_data.append((char)0xf8);
            gen_data.append(1,0x00);
            gen_data.append(1,0x01);
            send_data(WRITE32_MCU_PC_TO_MCU, gen_data);
        }
        Delay_MSec(30);
        //RST = 0
        {
            QByteArray gen_data;
            gen_data.append(1,0x00);
            gen_data.append(1,RESET_MCU_MCU_TO_PC);
            gen_data.append(2,0x00);
            send_data(WRITE16_IN_PC_TO_MCU, gen_data);
        }

        //RST = 1
        {
            QByteArray gen_data;
            gen_data.append(1,0x00);
            gen_data.append(1,RESET_MCU_MCU_TO_PC);
            gen_data.append(1,0x00);
            gen_data.append(1,0x01);
            send_data(WRITE16_IN_PC_TO_MCU, gen_data);
        }

        //MCU 00 0x000000a0
        {
            QByteArray gen_data;
            gen_data.append(1,0x00);
            gen_data.append(3,0x00);
            gen_data.append(1,0xa0);
            send_data(WRITE32_MCU_PC_TO_MCU, gen_data);
        }

        //MCU 02 0x00000080
        {
            QByteArray gen_data;
            gen_data.append(1,0x02);
            gen_data.append(3,0x00);
            gen_data.append(1,0x80);
            send_data(WRITE32_MCU_PC_TO_MCU, gen_data);
        }
        //MCU 00 0x000000a1
        {
            QByteArray gen_data;
            gen_data.append(1,0x00);
            gen_data.append(3,0x00);
            gen_data.append(1,0xa1);
            send_data(WRITE32_MCU_PC_TO_MCU, gen_data);
        }

        //HELLO
        {
            QByteArray gen_data;
            gen_data.append((program_version>>24)&0x0ff);
            gen_data.append((program_version>>16)&0x0ff);
            gen_data.append((program_version>>8)&0x0ff);
            gen_data.append((program_version)&0x0ff);
            send_data(HELLO_PC_TO_MCU, gen_data);
        }
    }
    //HELLO
    {
        QByteArray gen_data;
        gen_data.append(HELLO_PC_TO_MCU);
        gen_data.append(0x08);
        gen_data.append(2,0xFF);
        gen_data.append((program_version>>24)&0x0ff);
        gen_data.append((program_version>>16)&0x0ff);
        gen_data.append((program_version>>8)&0x0ff);
        gen_data.append((program_version)&0x0ff);
        myusbthread->send_data(gen_data.leftJustified(64, 0x00, true));
    }
    sender_timer->start(1);
    ui->textEdit_information->append(QString::fromUtf8(u8"开始下载：") + QDateTime::currentDateTime().toString("hh:mm:ss.zzz"));
}

void MainWindow::refresh_button()
{
    if(hid_isopen)
        ui->pushButton_openclose->setText(QString::fromUtf8(u8"断开连接"));
    else
        ui->pushButton_openclose->setText(QString::fromUtf8(u8"连接设备"));
    ui->pushButton_StartDownload->setEnabled(hid_isopen & load_bin & !downloading);
    ui->pushButton_StartDownloadFlash->setEnabled(hid_isopen & load_bin & !downloading);
    ui->comboBox_device->setEnabled(!hid_isopen & !downloading);
    ui->pushButton_openclose->setEnabled(!downloading);
    ui->pushButton_GetMCUID->setEnabled(hid_isopen & !downloading);
    ui->pushButton_emptyFlash->setEnabled(hid_isopen & !downloading);
}


/*************************************************
Function: hexStringtoByteArray()
Description: 十六进制字串转化为十六进制编码
Calls:formatString()
Called By:
Input:hex
Return:QByteArray
*************************************************/
QByteArray MainWindow::hexStrToByteArray(QString hex)
{
    QByteArray ret;
    hex = hex.trimmed();
    //formatString(hex,2,QChar(' '));
    qDebug() << hex;
    QStringList slist=hex.split(" ");
    qDebug() << slist;
    foreach(QString str,slist)
    {
        qDebug() << str;
        if(!str.isEmpty())
            ret.append((char)str.toInt(0,16)&0xFF);
    }
    return ret;
}
/*************************************************
Function:formatString()
Description: 将十六进制字串每字节中间加空格分隔
Calls:NONE
Called By:hexStrToByteArray()
Input: org->待处理的字串
       n->间隔数默认为2
       ch->分隔标志，在此取空格
Return: void
*************************************************/
void MainWindow::formatString(QString &str, int n=2,const QChar &ch=QChar(' '))
{
    int size= str.size();
    int space= qRound(size*1.0/n+0.5)-1;
    if(space<=0)
        return;
    for(int i=0,pos=n;i<space;++i,pos+=(n+1))
    {
        str.insert(pos,ch);
    }
}



bool MainWindow::eventFilter(QObject *obj, QEvent *event)
{
    return QObject::eventFilter(obj, event);
}


void MainWindow::send_data(uint8_t command, QByteArray & data)
{
    QByteArray gen_data;
    uint8_t size = 0;
    size = 2 + 2 + data.size();
    gen_data.append(command);
    gen_data.append(size);
    gen_data.append((char)((command_num>>8)&0x0ff));
    gen_data.append((char)(command_num&0x0ff));
    command_num++;
    gen_data.append(data);
    myusbthread->send_data(gen_data.leftJustified(64, 0x00, true));
}

void MainWindow::send_bin_data(uint8_t command, QByteArray & data)
{
    QByteArray gen_data;
    uint8_t size = 0;
    size = 2 + 2 + data.size();
    gen_data.append(command);
    gen_data.append(size);
    gen_data.append((char)((download_count>>8)&0x0ff));
    gen_data.append((char)(download_count&0x0ff));
    gen_data.append(data);
#if DEBUG_WRITE_BIN_FILE
    save_debug_bin.write(data.toHex(' '));
    save_debug_bin.flush();
#endif
    myusbthread->send_data(gen_data.leftJustified(64, 0x00, true));
}

void MainWindow::on_comboBox_device_currentIndexChanged(int index)
{

}

void MainWindow::Delay_MSec(unsigned int msec)
{
    QEventLoop loop;
    QTimer::singleShot(msec, &loop, SLOT(quit()));
    loop.exec();
}


void MainWindow::on_pushButton_StartDownloadFlash_clicked()
{
    write_flash = true;
    download_data();
}


void MainWindow::on_pushButton_GetMCUID_clicked()
{
    QByteArray gen_data;
    gen_data.append((program_version>>24)&0x0ff);
    gen_data.append((program_version>>16)&0x0ff);
    gen_data.append((program_version>>8)&0x0ff);
    gen_data.append((program_version)&0x0ff);
    send_data(HELLO_PC_TO_MCU, gen_data);
}


void MainWindow::on_pushButton_emptyFlash_clicked()
{
    //ui->textEdit_information->append("擦除数据:" + QDateTime::currentDateTime().toString("hh:mm:ss.zzz"));
    //flash F6 01 06 00 00
    {
        QByteArray gen_data;
        gen_data.append(1,0x01);
        gen_data.append(1,0x06);
        gen_data.append(2,0x00);
        send_data(WRITEN_FLASH_PC_TO_MCU, gen_data);
    }

    //flash F6 04 D8 00 00 00
    {
        QByteArray gen_data;
        gen_data.append(1,0x04);
        gen_data.append(1,0xD8);
        gen_data.append(3,0x00);
        send_data(WRITEN_FLASH_PC_TO_MCU, gen_data);
    }
    Delay_MSec(30);
    //flash F6 01 06 00 00
    {
        QByteArray gen_data;
        gen_data.append(1,0x01);
        gen_data.append(1,0x06);
        gen_data.append(2,0x00);
        send_data(WRITEN_FLASH_PC_TO_MCU, gen_data);
    }

    //flash F6 04 D8 01 00 00
    {
        QByteArray gen_data;
        gen_data.append(1,0x04);
        gen_data.append(1,0xD8);
        gen_data.append(1,0x01);
        gen_data.append(2,0x00);
        send_data(WRITEN_FLASH_PC_TO_MCU, gen_data);
    }
    Delay_MSec(30);
    //flash F6 01 06 00 00
    {
        QByteArray gen_data;
        gen_data.append(1,0x01);
        gen_data.append(1,0x06);
        gen_data.append(2,0x00);
        send_data(WRITEN_FLASH_PC_TO_MCU, gen_data);
    }

    //flash F6 04 D8 02 00 00
    {
        QByteArray gen_data;
        gen_data.append(1,0x04);
        gen_data.append(1,0xD8);
        gen_data.append(1,0x02);
        gen_data.append(2,0x00);
        send_data(WRITEN_FLASH_PC_TO_MCU, gen_data);
    }
    Delay_MSec(30);
    ui->textEdit_information->append(QString::fromUtf8(u8"擦除数据:") + QDateTime::currentDateTime().toString("hh:mm:ss.zzz"));
}

